#!/bin/bash
#跳板机推送
#二级推送

error_exit(){
	echo "ERROR: 跳板机推送失败,$1"
	echo "ERROR: 跳板机推送失败,$1" >> ${logFile}
    rm -rf ${projectPath}/${editionNum}/push_${jumpServerIp}.lock
	exit 1
}


rootPath=$1
projectName=$2
jumpServerIp=$3
recordName=$4
editionNum=$5
ssh_login_user=$6
ssh_key_file=$7
ssh_port=$8
shellPath=$9

parentIp=${10}
parentPort=${11}

projectPath=${12}

logFile="${rootPath}/Beetle/pushRecord/${recordName}/push.log"

loginUser=`whoami`
ssh_key_file=/home/${loginUser}/${ssh_key_file}

echo "跳板机推送开始,projectName=${projectName},jumpServerIp=${jumpServerIp}" >> ${logFile}

if [ ! ${projectPath} ]
then
    error_exit "参数存在空值projectPath=${projectPath}"
fi
if [ ! ${editionNum} ]
then
    error_exit "参数存在空值editionNum=${editionNum}"
fi

cd ${projectPath}/${editionNum} >> ${logFile} || error_exit "进入版本目录失败.${projectPath}/${editionNum}"

expect ${shellPath}/shell/init/beetle_validate_ssh.sh ${parentIp} ${loginUser} ${loginUser} ${parentPort} > /dev/null || error_exit "校验ssh免密登录失败,host=${parentIp}"

ssh ${loginUser}@${parentIp} -p ${parentPort} -i ${ssh_key_file} "expect /home/${ssh_login_user}/shell/beetle_validate_ssh.sh ${jumpServerIp} ${loginUser} ${loginUser} ${ssh_port} > /dev/null " || error_exit "校验二级跳板机ssh免密登录失败,host=${jumpServerIp}"


ssh ${loginUser}@${parentIp} -p ${parentPort} -i ${ssh_key_file} "ssh ${ssh_login_user}@${jumpServerIp} -p ${ssh_port} -i ${ssh_key_file} \"rm -rf ${projectPath}/${editionNum}\" " >> ${logFile} || error_exit "删除跳板机旧版本失败.${jumpServerIp}"

ssh ${loginUser}@${parentIp} -p ${parentPort} -i ${ssh_key_file} "ssh ${ssh_login_user}@${jumpServerIp} -p ${ssh_port} -i ${ssh_key_file} \"mkdir -p ${projectPath}/${editionNum}\" " >> ${logFile} || error_exit "创建版本目录失败.${jumpServerIp}"

ssh ${loginUser}@${parentIp} -p ${parentPort} -i ${ssh_key_file} "ssh ${ssh_login_user}@${jumpServerIp} -p ${ssh_port} -i ${ssh_key_file} \"mkdir -p ${projectPath}/${editionNum}/logs\" " >> ${logFile} || error_exit "创建版本日志目录失败.${jumpServerIp}"

ssh ${loginUser}@${parentIp} -p ${parentPort} -i ${ssh_key_file} "script -a ${projectPath}/${editionNum}/logs/push.log -q -c \"scp -v -P ${ssh_port} -i ${ssh_key_file} ${projectPath}/${editionNum}/push.tgz ${ssh_login_user}@${jumpServerIp}:${projectPath}/${editionNum}/\" " >> ${logFile} || error_exit "远程拷贝war包失败.${jumpServerIp}"

ssh ${loginUser}@${parentIp} -p ${parentPort} -i ${ssh_key_file} "ssh ${ssh_login_user}@${jumpServerIp} -p ${ssh_port} -i ${ssh_key_file} \"cd ${projectPath}/${editionNum};tar -zxf push.tgz\" " >> ${logFile} || error_exit "解压推送包失败.${jumpServerIp}"

echo "跳板机推送结束,projectName=${projectName},jumpServerIp=${jumpServerIp}" >> ${logFile}
echo "success"